#include "../Sock/Socket.hpp"
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
class httpClient
{
    std::string ip_;
    uint16_t    port_;
    int sockfd_;
    std::string domainName_;
public:
    httpClient( std::string& domainName,uint16_t port=80)
        :port_(port),domainName_(domainName)
    {
        ip_=Socket::getIpByDomainName(domainName);
    }


    void init()
    {
        sockfd_=Socket::CreateSock();
    }

    void start()
    {
        if(Socket::Connect(sockfd_,ip_,port_)!=0)
        {
            logMessage(WARNING,"connect err...");
        }

        serverIO();
    }

    void serverIO()
    {
        //构造请求
        std::string request="GET / HTTP/1.1\r\nHost: ";
        request+=domainName_;
        request+="\r\nConnection: close\r\n\r\n";  
        if (send(sockfd_, request.c_str(), request.size(), 0) == -1) {
            logMessage(ERROR,"send request err");
            exit(SEND_ERR);
        }

        // 接收响应
        char buffer[4096];
        ssize_t n = 0;
        while ((n = recv(sockfd_, buffer, sizeof(buffer)-1, 0)) > 0) 
        {
            buffer[n]=0;
            std::cout<<buffer<<std::endl;
        }
        
    }      

    

    ~httpClient()
    {
        if(sockfd_>=0)
            close(sockfd_);
    }

};